import address from '@/api/address'

const state = {
    list: [],
    requestSend: {
        list: false
    },
    selected: ''
}

const getters = {
    list: state => state.list
}

const actions = {
    async getAddressList ({state, commit}) {
        if (state.requestSend.list) return
        const {data, success} = await address.getAddressList()
        commit('addressList', data.list)
        commit('requestSend', 'list')
    },
    async toEdit ({commit}, addressInfo) {
        const {data, success} = await address.editAddress(addressInfo)
        if (success) commit('edit', addressInfo)
        return success
    },
    async toAdd ({commit}, addressInfo) {
        const {data, success} = await address.addAddress(addressInfo)
        addressInfo.address_id = data.address_id
        if (success) commit('add', addressInfo)
        return success
    },
    async toRemove ({commit}, addressId) {
        const {success} = await address.removeAddress(addressId)
        if (success) commit('remove', addressId)
        return success
    }
}

const mutations = {
    requestSend (state, item) {
        state.requestSend[item] = true
    },
    addressList (state, list) {
        state.list = list
    },
    edit (state, addressInfo) {
        const index = state.list.findIndex(a => a.address_id === addressInfo.address_id)
        state.list[index] = addressInfo
    },
    add (state, addressInfo) {
        state.list.push(addressInfo)
    },
    remove (state, addressId) {
        const index = state.list.findIndex(l => l.address_id === addressId)
        state.list.splice(index, 1)
    },
    selectAddress (state, addressId) {
        state.selected = addressId
    }
}

export default {
    state,
    getters,
    actions,
    mutations,
    namespaced: true
}
